package com.cs.controller.goods;

import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cs.controller.utils.ImageUpload;
import com.cs.controller.utils.R;

//import com.baomidou.mybatisplus.extension.api.R;
import com.cs.pojo.*;
import com.cs.service.IngredientInfo.IIngredientInfoService;
import com.cs.service.goodClassify.IGoodClassifyService;
import com.cs.service.goods.IgoodsService;
import com.cs.service.image.ImageService;
import com.cs.service.sweetness.ISweetnessService;
import com.cs.service.temperature.ITemperatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/goods")
public class goodsController_R {
    @Autowired
    private IgoodsService igoodsService;
    @Autowired
    private IGoodClassifyService igoodClassifyService;
    @Autowired
    private IIngredientInfoService iIngredientInfoService;
    @Autowired
    private ITemperatureService iTemperatureService;
    @Autowired
    private ISweetnessService iSweetnessService;

    @Autowired
    private ImageService imageService;
    /**
     * 获取全部商品
     * @return
     */
    @GetMapping()
    public R getAll(){
        LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Goods::getStatus,"1");
        List<Goods> goodsList = igoodsService.list(wrapper);
        //遍历原始数据列表，将每个商品按照分类添加到map中
        HashMap<String, List<Goods>> map = new HashMap<>();
        for (Goods goods : goodsList) {
            String classify=goods.getClassify();
            List<Goods> list=map.get(classify);
            if(list==null){
                list=new ArrayList<>();
                map.put(classify,list);
            }
            list.add(goods);
        }
        List<Map<String,Object>> resultList=new ArrayList<>();
        for (Map.Entry<String, List<Goods>> entry : map.entrySet()) {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("classify",entry.getKey());
            resultMap.put("goods",entry.getValue());
            resultList.add(resultMap);
        }

        return new R("200",resultList);
//        return new R("200",igoodsService.list());
//        return null;
    }
    /**
     * 添加商品
//     * @param goods
     * @return
     */
    @PostMapping()
    @Transactional
    public R save(@RequestParam("file")MultipartFile[] files,@ModelAttribute Goods  goods) throws Exception {

        ArrayList<String> list=imageService.uploadFileAvatar(files);
        goods.setImgFile(list.toString());
        if(igoodsService.save(goods)) {
            return new R("200", "添加成功");
        }else {
            return new R("400","添加失败");
        }
    }
    /**
     * 根据id修改商品信息
     * @param goods
     * @return
     */
    @PutMapping
    @Transactional
    public R update(@RequestParam(value = "file",required = false) MultipartFile[] files,@ModelAttribute Goods goods) throws Exception {
        ArrayList<String> resultImg=new ArrayList<>();
        String imgStr= goods.getImgFile();
        System.out.println(imgStr+"****imgStr***********");
        String[] newImg;
        if(!imgStr.equals("")){
         newImg=imgStr.substring(1, goods.getImgFile().length()).split(",");
            for (String s : newImg) {
                if(s!=""){
                    int i = s.lastIndexOf("/");
                    String s1=s.substring(i+1);
                    resultImg.add(s1);
                }
            }
        }
        if(files!=null){
            ArrayList<String> list = imageService.uploadFileAvatar(files);
            for (String s : list) {
                resultImg.add(s);
            }
        }
        goods.setImgFile(resultImg.toString());
        return new R("200",igoodsService.updateById(goods),"修改成功");
    }
    /**
     * 根据ID删除商品
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional
    public R delete(@PathVariable Integer id){
        return new R("200",igoodsService.removeById(id),"删除成功");
    }
    /**
     * 根据名称获取商品
     * @param goodsName
     * @return
     */
    @GetMapping("/{goodsName}")
    public R selectByName(@PathVariable String goodsName){
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>();
        lambdaQueryWrapper.like(Goods::getGoodsName,goodsName);
        return new R("200",igoodsService.list(lambdaQueryWrapper));
    }
    /**
     * 根据分类获取商品
     * @param Classify
     * @return
     */
    @GetMapping("/classify/{Classify}")
    public R selectByClassify(@PathVariable String Classify){
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>();
        lambdaQueryWrapper.eq(Goods::getClassify,Classify);
        return new R("200",igoodsService.list(lambdaQueryWrapper));
    }
    /**
     * 获取全部商品分类
     * @return
     */
    @GetMapping("/classify")
    public R getClassify(){
        return new R("200",igoodClassifyService.list());
    }
    /**
     * 添加商品分类
     * @param classify
     * @return
     */
    @PostMapping("/addClassify/{classify}")
    @Transactional
    public R addGoodClassify(@PathVariable String classify){
        GoodsClassify goodsClassify = new GoodsClassify();
        goodsClassify.setClassify(classify);
        return new R("200",igoodClassifyService.save(goodsClassify),"添加成功");
    }
    /**
     * 修改商品分类
     * @param goodsClassify
     * @return
     */
    @PutMapping("/updateClassify")
    @Transactional
    public R updateClassify(@RequestBody GoodsClassify goodsClassify){
        return new R("200",igoodClassifyService.updateById(goodsClassify),"修改成功");
    }
    /**
     * 分页查询商品
     * @param currentPage
     * @param pageSize
     * @param good
     * @return
     */
    @GetMapping("/page/{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Goods good){
        IPage<Goods> page = igoodsService.getPage(currentPage, pageSize,good);
        //如果当前页码值大于总页码值，重新执行查询操作，使用最大页码值作为当前页
        if (currentPage>page.getPages()){
            page=igoodsService.getPage((int) page.getPages(),pageSize,good);
        }
        return new R("200",page);
    }
    /**
     * 修改商品上架状态
     * @param goodId
     * @return
     */
    @PutMapping("/status/{goodId}")
    @Transactional
    public R updateGoodStatus(@PathVariable int goodId){
        Goods good = igoodsService.getById(goodId);
        int status;
        if(good.getStatus()==0){
            status=1;
        }else {
            status=0;
        }
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",goodId);
        updateWrapper.set("status",status);

        return new R("200",igoodsService.update(good, updateWrapper),"修改成功");
    }
    /**
     * 删除商品分类
     * @param id
     * @return
     */
    @DeleteMapping("/classify/{id}")
    @Transactional
    public R deleteClassify(@PathVariable int id){
        return new R("200",igoodClassifyService.removeById(id),"删除成功");
    }

    /**
     * 根据分类查询商品 分页
     * @param currentPage
     * @param pageSize
     * @param classify
     * @return
     */
    @GetMapping("/pageByClassify/{currentPage}/{pageSize}/{classify}")
    public R getPageByClassify(@PathVariable int currentPage, @PathVariable int pageSize,@PathVariable String classify){
        IPage<Goods> page = igoodsService.getPageByClassify(currentPage, pageSize,classify);
        //如果当前页码值大于总页码值，重新执行查询操作，使用最大页码值作为当前页
        if (currentPage>page.getPages()){
            page=igoodsService.getPageByClassify((int) page.getPages(),pageSize,classify);
        }
        return new R("200",page);
    }

    /**
     * 根据名称获取商品 分页
     * @param currentPage
     * @param pageSize
     * @param goodName
     * @return
     */
    @GetMapping("/pageByGoodName/{currentPage}/{pageSize}/{goodName}")
    public R getPageByGoodName(@PathVariable int currentPage, @PathVariable int pageSize,@PathVariable String goodName){
        IPage<Goods> page = igoodsService.getPageByGoodName(currentPage, pageSize,goodName);
        //如果当前页码值大于总页码值，重新执行查询操作，使用最大页码值作为当前页
        if (currentPage>page.getPages()){
            page=igoodsService.getPageByGoodName((int) page.getPages(),pageSize,goodName);
        }
        return new R("200",page);
    }

    @GetMapping("/choice")
    public R getIngredient(){
        List<IngredientInfo> ingredientInfoList = iIngredientInfoService.list();
        List<Sweetness> sweetnessList = iSweetnessService.list();
        List<Temperature> temperatureList = iTemperatureService.list();
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(sweetnessList);
        objects.add(temperatureList);
        objects.add(ingredientInfoList);
        return new R("200",objects);
    }
}
